﻿// Decompiled with JetBrains decompiler
// Type: SandBox.Issues.ProdigalSonIssueBehavior
// Assembly: SandBox, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 75BA0B61-63FF-423A-8603-0A2974B621BB
// Assembly location: D:\steam\steamapps\common\Mount & Blade II Bannerlord\Modules\SandBox\bin\Win64_Shipping_Client\SandBox.dll

using Helpers;
using SandBox.Conversation.MissionLogics;
using SandBox.Missions.AgentBehaviors;
using SandBox.Missions.MissionLogics;
using System;
using System.Collections.Generic;
using System.Linq;
using TaleWorlds.CampaignSystem;
using TaleWorlds.CampaignSystem.Actions;
using TaleWorlds.CampaignSystem.AgentOrigins;
using TaleWorlds.CampaignSystem.CharacterDevelopment;
using TaleWorlds.CampaignSystem.Conversation;
using TaleWorlds.CampaignSystem.Conversation.Persuasion;
using TaleWorlds.CampaignSystem.Encounters;
using TaleWorlds.CampaignSystem.Extensions;
using TaleWorlds.CampaignSystem.Issues;
using TaleWorlds.CampaignSystem.Map;
using TaleWorlds.CampaignSystem.MapEvents;
using TaleWorlds.CampaignSystem.Party;
using TaleWorlds.CampaignSystem.Roster;
using TaleWorlds.CampaignSystem.Settlements;
using TaleWorlds.CampaignSystem.Settlements.Locations;
using TaleWorlds.Core;
using TaleWorlds.Engine;
using TaleWorlds.Library;
using TaleWorlds.Localization;
using TaleWorlds.MountAndBlade;
using TaleWorlds.ObjectSystem;
using TaleWorlds.SaveSystem;

#nullable disable
namespace SandBox.Issues
{
  public class ProdigalSonIssueBehavior : CampaignBehaviorBase
  {
    private const IssueBase.IssueFrequency ProdigalSonIssueFrequency = IssueBase.IssueFrequency.Rare;
    private const int AgeLimitForSon = 35;
    private const int AgeLimitForIssueOwner = 30;
    private const int MinimumAgeDifference = 10;

    public override void RegisterEvents()
    {
      CampaignEvents.OnCheckForIssueEvent.AddNonSerializedListener((object) this, new Action<Hero>(this.CheckForIssue));
    }

    public override void SyncData(IDataStore dataStore)
    {
    }

    public void CheckForIssue(Hero hero)
    {
      Hero selectedHero;
      Hero targetHero;
      if (this.ConditionsHold(hero, out selectedHero, out targetHero))
        Campaign.Current.IssueManager.AddPotentialIssueData(hero, new PotentialIssueData(new PotentialIssueData.StartIssueDelegate(this.OnStartIssue), typeof (ProdigalSonIssueBehavior.ProdigalSonIssue), IssueBase.IssueFrequency.Rare, (object) new Tuple<Hero, Hero>(selectedHero, targetHero)));
      else
        Campaign.Current.IssueManager.AddPotentialIssueData(hero, new PotentialIssueData(typeof (ProdigalSonIssueBehavior.ProdigalSonIssue), IssueBase.IssueFrequency.Rare));
    }

    private bool ConditionsHoldForSettlement(Settlement settlement, Hero issueGiver)
    {
      return settlement.IsTown && settlement != issueGiver.CurrentSettlement && settlement.OwnerClan != issueGiver.Clan && settlement.OwnerClan != Clan.PlayerClan && settlement.HeroesWithoutParty.FirstOrDefault<Hero>((Func<Hero, bool>) (x => x.CanHaveQuestsOrIssues() && x.IsGangLeader)) != null && settlement.LocationComplex.GetListOfLocations().AnyQ<Location>((Func<Location, bool>) (x => x.CanBeReserved && !x.IsReserved));
    }

    private bool ConditionsHold(Hero issueGiver, out Hero selectedHero, out Hero targetHero)
    {
      selectedHero = (Hero) null;
      targetHero = (Hero) null;
      if (issueGiver.IsLord && !issueGiver.IsPrisoner && issueGiver.Clan != Clan.PlayerClan && (double) issueGiver.Age > 30.0 && issueGiver.GetTraitLevel(DefaultTraits.Mercy) <= 0 && (issueGiver.CurrentSettlement != null || issueGiver.PartyBelongedTo != null))
      {
        selectedHero = issueGiver.Clan.Lords.GetRandomElementWithPredicate<Hero>((Func<Hero, bool>) (x => x.IsActive && !x.IsFemale && (double) x.Age < 35.0 && (int) x.Age + 10 <= (int) issueGiver.Age && !x.IsPrisoner && x.CanHaveQuestsOrIssues() && x.PartyBelongedTo == null && x.CurrentSettlement != null && x.GovernorOf == null && x.GetTraitLevel(DefaultTraits.Honor) + x.GetTraitLevel(DefaultTraits.Calculating) < 0));
        if (selectedHero != null)
        {
          IMapPoint mapPoint = (IMapPoint) issueGiver.CurrentSettlement ?? (IMapPoint) issueGiver.PartyBelongedTo;
          int maxValue = 0;
          int num1 = -1;
          do
          {
            num1 = SettlementHelper.FindNextSettlementAroundMapPoint(mapPoint, 150f, num1);
            if (num1 >= 0 && this.ConditionsHoldForSettlement(Settlement.All[num1], issueGiver))
              ++maxValue;
          }
          while (num1 >= 0);
          if (maxValue > 0)
          {
            int num2 = MBRandom.RandomInt(maxValue);
            int num3 = -1;
            do
            {
              num3 = SettlementHelper.FindNextSettlementAroundMapPoint(mapPoint, 150f, num3);
              if (num3 >= 0 && this.ConditionsHoldForSettlement(Settlement.All[num3], issueGiver))
              {
                --num2;
                if (num2 < 0)
                {
                  targetHero = Settlement.All[num3].HeroesWithoutParty.FirstOrDefault<Hero>((Func<Hero, bool>) (x => x.CanHaveQuestsOrIssues() && x.IsGangLeader));
                  break;
                }
              }
            }
            while (num3 >= 0);
          }
        }
      }
      return selectedHero != null && targetHero != null;
    }

    private IssueBase OnStartIssue(in PotentialIssueData pid, Hero issueOwner)
    {
      Tuple<Hero, Hero> relatedObject = pid.RelatedObject as Tuple<Hero, Hero>;
      return (IssueBase) new ProdigalSonIssueBehavior.ProdigalSonIssue(issueOwner, relatedObject.Item1, relatedObject.Item2);
    }

    public class ProdigalSonIssueTypeDefiner : SaveableTypeDefiner
    {
      public ProdigalSonIssueTypeDefiner()
        : base(345000)
      {
      }

      protected override void DefineClassTypes()
      {
        this.AddClassDefinition(typeof (ProdigalSonIssueBehavior.ProdigalSonIssue), 1);
        this.AddClassDefinition(typeof (ProdigalSonIssueBehavior.ProdigalSonIssueQuest), 2);
      }
    }

    public class ProdigalSonIssue : IssueBase
    {
      private const int IssueDurationInDays = 50;
      private const int QuestDurationInDays = 24;
      private const int TroopTierForAlternativeSolution = 2;
      private const int RequiredSkillValueForAlternativeSolution = 120;
      [SaveableField(10)]
      private readonly Hero _prodigalSon;
      [SaveableField(20)]
      private readonly Hero _targetHero;
      [SaveableField(30)]
      private readonly Location _targetHouse;
      private Settlement _targetSettlement;

      public override IssueBase.AlternativeSolutionScaleFlag AlternativeSolutionScaleFlags
      {
        get => IssueBase.AlternativeSolutionScaleFlag.FailureRisk;
      }

      private Clan Clan => this.IssueOwner.Clan;

      protected override int RewardGold
      {
        get => 1200 + (int) (3000.0 * (double) this.IssueDifficultyMultiplier);
      }

      public override TextObject IssueBriefByIssueGiver
      {
        get
        {
          TextObject parent = new TextObject("{=5a6KlSXt}I have a problem. [ib:normal2][if:convo_pondering]My young kinsman {PRODIGAL_SON.LINK} has gone to town to have fun, drinking, wenching and gambling. Many young men do that, but it seems he was a bit reckless. Now he sends news that he owes a large sum of money to {TARGET_HERO.LINK}, one of the local gang bosses in the city of {SETTLEMENT_LINK}. These ruffians are holding him as a “guest” in their house until someone pays his debt.");
          StringHelpers.SetCharacterProperties("PRODIGAL_SON", this._prodigalSon.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject, parent);
          parent.SetTextVariable("SETTLEMENT_LINK", this._targetSettlement.EncyclopediaLinkWithName);
          return parent;
        }
      }

      public override TextObject IssueAcceptByPlayer
      {
        get => new TextObject("{=YtS3cgto}What are you planning to do?");
      }

      public override TextObject IssueQuestSolutionExplanationByIssueGiver
      {
        get
        {
          TextObject explanationByIssueGiver = new TextObject("{=ZC1slXw1}I'm not inclined to pay the debt. [ib:closed][if:convo_worried]I'm not going to reward this kind of lawlessness, when even the best families aren't safe. I've sent word to the lord of {SETTLEMENT_NAME} but I can't say I expect to hear back, what with the wars and all. I want someone to go there and free the lad. You could pay, I suppose, but I'd prefer it if you taught those bastards a lesson. I'll pay you either way but obviously you get to keep more if you use force.");
          explanationByIssueGiver.SetTextVariable("SETTLEMENT_NAME", this._targetSettlement.EncyclopediaLinkWithName);
          return explanationByIssueGiver;
        }
      }

      public override TextObject IssuePlayerResponseAfterAlternativeExplanation
      {
        get => new TextObject("{=4zf1lg6L}I could go myself, or send a companion.");
      }

      public override TextObject IssueAlternativeSolutionExplanationByIssueGiver
      {
        get
        {
          TextObject explanationByIssueGiver = new TextObject("{=CWbAoGRu}Yes, I don't care how you solve it. [if:convo_normal]Just solve it any way you like. I reckon {NEEDED_MEN_COUNT} led by someone who knows how to handle thugs could solve this in about {ALTERNATIVE_SOLUTION_DURATION} days. I'd send my own men but it could cause complications for us to go marching in wearing our clan colors in another lord's territory.");
          explanationByIssueGiver.SetTextVariable("NEEDED_MEN_COUNT", this.GetTotalAlternativeSolutionNeededMenCount());
          explanationByIssueGiver.SetTextVariable("ALTERNATIVE_SOLUTION_DURATION", this.GetTotalAlternativeSolutionDurationInDays());
          return explanationByIssueGiver;
        }
      }

      public override TextObject IssueQuestSolutionAcceptByPlayer
      {
        get => new TextObject("{=aKbyJsho}I will free your kinsman myself.");
      }

      public override TextObject IssueAlternativeSolutionAcceptByPlayer
      {
        get
        {
          TextObject solutionAcceptByPlayer = new TextObject("{=PuuVGOyM}I will send {NEEDED_MEN_COUNT} of my men with one of my lieutenants for {ALTERNATIVE_SOLUTION_DURATION} days to help you.");
          solutionAcceptByPlayer.SetTextVariable("NEEDED_MEN_COUNT", this.GetTotalAlternativeSolutionNeededMenCount());
          solutionAcceptByPlayer.SetTextVariable("ALTERNATIVE_SOLUTION_DURATION", this.GetTotalAlternativeSolutionDurationInDays());
          return solutionAcceptByPlayer;
        }
      }

      public override TextObject IssueDiscussAlternativeSolution
      {
        get
        {
          return new TextObject("{=qxhMagyZ}I'm glad someone's on it.[if:convo_relaxed_happy] Just see that they do it quickly.");
        }
      }

      public override TextObject IssueAlternativeSolutionResponseByIssueGiver
      {
        get
        {
          return new TextObject("{=mDXzDXKY}Very good. [if:convo_relaxed_happy]I'm sure you'll chose competent men to bring our boy back.");
        }
      }

      protected override TextObject AlternativeSolutionStartLog
      {
        get
        {
          TextObject parent = new TextObject("{=Z9sp21rl}{QUEST_GIVER.LINK}, a lord from the {QUEST_GIVER_CLAN} clan, asked you to free {?QUEST_GIVER.GENDER}her{?}his{\\?} relative. The young man is currently held by {TARGET_HERO.LINK} a local gang leader because of his debts. {?QUEST_GIVER.GENDER}Lady{?}Lord{\\?} {QUEST_GIVER.LINK} has given you enough gold to settle {?QUEST_GIVER.GENDER}her{?}his{\\?} debts but {?QUEST_GIVER.GENDER}she{?}he{\\?} encourages you to keep the money to yourself and make an example of these criminals so no one would dare to hold a nobleman again. You have sent {COMPANION.LINK} and {NEEDED_MEN_COUNT} men to take care of the situation for you. They should be back in {ALTERNATIVE_SOLUTION_DURATION} days.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.IssueOwner.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("COMPANION", this.AlternativeSolutionHero.CharacterObject, parent);
          parent.SetTextVariable("QUEST_GIVER_CLAN", this.IssueOwner.Clan.EncyclopediaLinkWithName);
          parent.SetTextVariable("SETTLEMENT", this._targetSettlement.EncyclopediaLinkWithName);
          parent.SetTextVariable("NEEDED_MEN_COUNT", this.GetTotalAlternativeSolutionNeededMenCount());
          parent.SetTextVariable("ALTERNATIVE_SOLUTION_DURATION", this.GetTotalAlternativeSolutionDurationInDays());
          return parent;
        }
      }

      public override TextObject IssueAlternativeSolutionSuccessLog
      {
        get
        {
          TextObject parent = new TextObject("{=IXnvQ8kG}{COMPANION.LINK} and the men you sent with {?COMPANION.GENDER}her{?}him{\\?} safely return with the news of success. {QUEST_GIVER.LINK} is happy and sends you {?QUEST_GIVER.GENDER}her{?}his{\\?} regards with {REWARD}{GOLD_ICON} the money he promised.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.IssueOwner.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("COMPANION", this.AlternativeSolutionHero.CharacterObject, parent);
          parent.SetTextVariable("REWARD", this.RewardGold);
          return parent;
        }
      }

      public override bool IsThereAlternativeSolution => true;

      public override int AlternativeSolutionBaseNeededMenCount
      {
        get => 1 + MathF.Ceiling(3f * this.IssueDifficultyMultiplier);
      }

      protected override int AlternativeSolutionBaseDurationInDaysInternal
      {
        get => 7 + MathF.Ceiling(7f * this.IssueDifficultyMultiplier);
      }

      protected override int CompanionSkillRewardXP
      {
        get => (int) (700.0 + 900.0 * (double) this.IssueDifficultyMultiplier);
      }

      public override bool IsThereLordSolution => false;

      public override TextObject Title
      {
        get
        {
          TextObject title = new TextObject("{=Mr2rt8g8}Prodigal son of {CLAN_NAME}");
          title.SetTextVariable("CLAN_NAME", this.Clan.Name);
          return title;
        }
      }

      public override TextObject Description
      {
        get
        {
          TextObject parent = new TextObject("{=5puy0Jle}{ISSUE_OWNER.NAME} asks the player to aid a young clan member. He is supposed to have huge gambling debts so the gang leaders holds him as a hostage. You are asked to retrieve him any way possible.");
          StringHelpers.SetCharacterProperties("ISSUE_OWNER", this.IssueOwner.CharacterObject, parent);
          return parent;
        }
      }

      public ProdigalSonIssue(Hero issueOwner, Hero prodigalSon, Hero targetGangHero)
        : base(issueOwner, CampaignTime.DaysFromNow(50f))
      {
        this._prodigalSon = prodigalSon;
        this._targetHero = targetGangHero;
        this._targetSettlement = this._targetHero.CurrentSettlement;
        this._targetHouse = this._targetSettlement.LocationComplex.GetListOfLocations().FirstOrDefault<Location>((Func<Location, bool>) (x => x.CanBeReserved && !x.IsReserved));
        TextObject textObject = new TextObject("{=EZ19JOGj}{MENTOR.NAME}'s House");
        StringHelpers.SetCharacterProperties("MENTOR", this._targetHero.CharacterObject, textObject);
        this._targetHouse.ReserveLocation(textObject, textObject);
        DisableHeroAction.Apply(this._prodigalSon);
      }

      public override void OnHeroCanHaveQuestOrIssueInfoIsRequested(Hero hero, ref bool result)
      {
        if (hero != this._targetHero && hero != this._prodigalSon)
          return;
        result = false;
      }

      protected override float GetIssueEffectAmountInternal(IssueEffect issueEffect)
      {
        return issueEffect == DefaultIssueEffects.IssueOwnerPower ? -0.2f : 0.0f;
      }

      public override (SkillObject, int) GetAlternativeSolutionSkill(Hero hero)
      {
        return (hero.GetSkillValue(DefaultSkills.Charm) >= hero.GetSkillValue(DefaultSkills.Roguery) ? DefaultSkills.Charm : DefaultSkills.Roguery, 120);
      }

      protected override void OnGameLoad()
      {
        Town town = Town.AllTowns.FirstOrDefault<Town>((Func<Town, bool>) (x => x.Settlement.LocationComplex.GetListOfLocations().Contains<Location>(this._targetHouse)));
        if (town == null)
          return;
        this._targetSettlement = town.Settlement;
      }

      protected override void HourlyTick()
      {
      }

      protected override QuestBase GenerateIssueQuest(string questId)
      {
        return (QuestBase) new ProdigalSonIssueBehavior.ProdigalSonIssueQuest(questId, this.IssueOwner, this._targetHero, this._prodigalSon, this._targetHouse, this.IssueDifficultyMultiplier, CampaignTime.DaysFromNow(24f), this.RewardGold);
      }

      public override IssueBase.IssueFrequency GetFrequency() => IssueBase.IssueFrequency.Rare;

      protected override bool CanPlayerTakeQuestConditions(
        Hero issueGiver,
        out IssueBase.PreconditionFlags flag,
        out Hero relationHero,
        out SkillObject skill)
      {
        bool questConditions = (double) issueGiver.GetRelationWithPlayer() >= -10.0 && !issueGiver.MapFaction.IsAtWarWith(Hero.MainHero.MapFaction) && Clan.PlayerClan.Tier >= 1;
        flag = questConditions ? IssueBase.PreconditionFlags.None : (!issueGiver.MapFaction.IsAtWarWith(Hero.MainHero.MapFaction) ? (Clan.PlayerClan.Tier >= 1 ? IssueBase.PreconditionFlags.Relation : IssueBase.PreconditionFlags.ClanTier) : IssueBase.PreconditionFlags.AtWar);
        relationHero = issueGiver;
        skill = (SkillObject) null;
        return questConditions;
      }

      public override bool IssueStayAliveConditions() => this._targetHero.IsActive;

      protected override void CompleteIssueWithTimedOutConsequences()
      {
      }

      public override bool DoTroopsSatisfyAlternativeSolution(
        TroopRoster troopRoster,
        out TextObject explanation)
      {
        explanation = TextObject.Empty;
        return QuestHelper.CheckRosterForAlternativeSolution(troopRoster, this.GetTotalAlternativeSolutionNeededMenCount(), ref explanation, 2);
      }

      public override bool IsTroopTypeNeededByAlternativeSolution(CharacterObject character)
      {
        return character.Tier >= 2;
      }

      public override bool AlternativeSolutionCondition(out TextObject explanation)
      {
        explanation = TextObject.Empty;
        return QuestHelper.CheckRosterForAlternativeSolution(MobileParty.MainParty.MemberRoster, this.GetTotalAlternativeSolutionNeededMenCount(), ref explanation, 2);
      }

      protected override void AlternativeSolutionEndWithSuccessConsequence()
      {
        this.AlternativeSolutionHero.AddSkillXp(DefaultSkills.Charm, (float) (int) (700.0 + 900.0 * (double) this.IssueDifficultyMultiplier));
        this.RelationshipChangeWithIssueOwner = 5;
        GainRenownAction.Apply(Hero.MainHero, 3f);
      }

      protected override void AlternativeSolutionEndWithFailureConsequence()
      {
        this.RelationshipChangeWithIssueOwner = -5;
      }

      protected override void OnIssueFinalized()
      {
        if (this._prodigalSon.HeroState != Hero.CharacterStates.Disabled)
          return;
        this._prodigalSon.ChangeState(Hero.CharacterStates.Released);
      }

      internal static void AutoGeneratedStaticCollectObjectsProdigalSonIssue(
        object o,
        List<object> collectedObjects)
      {
        ((MBObjectBase) o).AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      protected override void AutoGeneratedInstanceCollectObjects(List<object> collectedObjects)
      {
        base.AutoGeneratedInstanceCollectObjects(collectedObjects);
        collectedObjects.Add((object) this._prodigalSon);
        collectedObjects.Add((object) this._targetHero);
        collectedObjects.Add((object) this._targetHouse);
      }

      internal static object AutoGeneratedGetMemberValue_prodigalSon(object o)
      {
        return (object) ((ProdigalSonIssueBehavior.ProdigalSonIssue) o)._prodigalSon;
      }

      internal static object AutoGeneratedGetMemberValue_targetHero(object o)
      {
        return (object) ((ProdigalSonIssueBehavior.ProdigalSonIssue) o)._targetHero;
      }

      internal static object AutoGeneratedGetMemberValue_targetHouse(object o)
      {
        return (object) ((ProdigalSonIssueBehavior.ProdigalSonIssue) o)._targetHouse;
      }
    }

    public class ProdigalSonIssueQuest : QuestBase
    {
      private const PersuasionDifficulty Difficulty = PersuasionDifficulty.Hard;
      private const int DistanceSquaredToStartConversation = 4;
      private const int CrimeRatingCancelRelationshipPenalty = -5;
      private const int CrimeRatingCancelHonorXpPenalty = -50;
      [SaveableField(10)]
      private readonly Hero _targetHero;
      [SaveableField(20)]
      private readonly Hero _prodigalSon;
      [SaveableField(30)]
      private bool _playerTalkedToTargetHero;
      [SaveableField(40)]
      private readonly Location _targetHouse;
      [SaveableField(50)]
      private readonly float _questDifficulty;
      [SaveableField(60)]
      private bool _isHouseFightFinished;
      [SaveableField(70)]
      private bool _playerTriedToPersuade;
      private PersuasionTask _task;
      private bool _isMissionFightInitialized;
      private bool _isFirstMissionTick;

      public override TextObject Title
      {
        get
        {
          TextObject title = new TextObject("{=7kqz1LlI}Prodigal son of {CLAN}");
          title.SetTextVariable("CLAN", this.QuestGiver.Clan.Name);
          return title;
        }
      }

      public override bool IsRemainingTimeHidden => false;

      private Settlement Settlement => this._targetHero.CurrentSettlement;

      private int DebtWithInterest => (int) ((double) this.RewardGold * 1.1000000238418579);

      private TextObject QuestStartedLog
      {
        get
        {
          TextObject parent = new TextObject("{=CXw9a1i5}{QUEST_GIVER.LINK}, a {?QUEST_GIVER.GENDER}lady{?}lord{\\?} from the {QUEST_GIVER_CLAN} clan, asked you to go to {SETTLEMENT} to free {?QUEST_GIVER.GENDER}her{?}his{\\?} relative. The young man is currently held by {TARGET_HERO.LINK}, a local gang leader, because of his debts. {QUEST_GIVER.LINK} has suggested that you make an example of the gang so no one would dare to hold a nobleman again. {?QUEST_GIVER.GENDER}She{?}He{\\?} said you can easily find the house in which the young nobleman is held in the town square.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject, parent);
          parent.SetTextVariable("QUEST_GIVER_CLAN", this.QuestGiver.Clan.EncyclopediaLinkWithName);
          parent.SetTextVariable("SETTLEMENT", this.Settlement.EncyclopediaLinkWithName);
          return parent;
        }
      }

      private TextObject PlayerDefeatsThugsQuestSuccessLog
      {
        get
        {
          TextObject parent = new TextObject("{=axLR9bQo}You have defeated the thugs that held {PRODIGAL_SON.LINK} as {QUEST_GIVER.LINK} has asked you to. {?QUEST_GIVER.GENDER}Lady{?}Lord{\\?} {QUEST_GIVER.LINK} soon sends {?QUEST_GIVER.GENDER}her{?}his{\\?} best regards and a sum of {REWARD}{GOLD_ICON} as a reward.");
          StringHelpers.SetCharacterProperties("PRODIGAL_SON", this._prodigalSon.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          parent.SetTextVariable("REWARD", this.RewardGold);
          return parent;
        }
      }

      private TextObject PlayerPaysTheDebtQuestSuccessLog
      {
        get
        {
          TextObject parent = new TextObject("{=skMoB7c6}You have paid the debt that {PRODIGAL_SON.LINK} owes. True to {?TARGET_HERO.GENDER}her{?}his{\\?} word {TARGET_HERO.LINK} releases the boy immediately. Soon after, {?QUEST_GIVER.GENDER}Lady{?}Lord{\\?} {QUEST_GIVER.LINK} sends {?QUEST_GIVER.GENDER}her{?}his{\\?} best regards and a sum of {REWARD}{GOLD_ICON} as a reward.");
          StringHelpers.SetCharacterProperties("PRODIGAL_SON", this._prodigalSon.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          parent.SetTextVariable("REWARD", this.RewardGold);
          return parent;
        }
      }

      private TextObject QuestTimeOutFailLog
      {
        get
        {
          TextObject parent = new TextObject("{=dmijPqWn}You have failed to extract {QUEST_GIVER.LINK}'s relative captive in time. They have moved the boy to a more secure place. Its impossible to find him now. {QUEST_GIVER.LINK} will have to deal with {TARGET_HERO.LINK} himself now. {?QUEST_GIVER.GENDER}She{?}He{\\?} won't be happy to hear this.");
          StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject PlayerHasDefeatedQuestFailLog
      {
        get
        {
          TextObject parent = new TextObject("{=d5a8xQos}You have failed to defeat the thugs that keep {QUEST_GIVER.LINK}'s relative captive. After your assault you learn that they move the boy to a more secure place. Now its impossible to find him. {QUEST_GIVER.LINK} will have to deal with {TARGET_HERO.LINK} himself now. {?QUEST_GIVER.GENDER}She{?}He{\\?} won't be happy to hear this.");
          StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject PlayerConvincesGangLeaderQuestSuccessLog
      {
        get
        {
          TextObject parent = new TextObject("{=Rb7g1U2s}You have convinced {TARGET_HERO.LINK} to release {PRODIGAL_SON.LINK}. Soon after, {?QUEST_GIVER.GENDER}Lady{?}Lord{\\?} {QUEST_GIVER.LINK} sends {?QUEST_GIVER.GENDER}her{?}his{\\?} best regards and a sum of {REWARD}{GOLD_ICON} as a reward.");
          StringHelpers.SetCharacterProperties("PRODIGAL_SON", this._prodigalSon.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          parent.SetTextVariable("REWARD", this.RewardGold);
          return parent;
        }
      }

      private TextObject WarDeclaredQuestCancelLog
      {
        get
        {
          TextObject parent = new TextObject("{=VuqZuSe2}Your clan is now at war with the {QUEST_GIVER.LINK}'s faction. Your agreement has been canceled.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject PlayerDeclaredWarQuestLogText
      {
        get
        {
          TextObject parent = new TextObject("{=bqeWVVEE}Your actions have started a war with {QUEST_GIVER.LINK}'s faction. {?QUEST_GIVER.GENDER}She{?}He{\\?} cancels your agreement and the quest is a failure.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject CrimeRatingCancelLog
      {
        get
        {
          TextObject to = new TextObject("{=oulvvl52}You are accused in {SETTLEMENT} of a crime, and {QUEST_GIVER.LINK} no longer trusts you in this matter.");
          to.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject);
          to.SetTextVariable("SETTLEMENT", this.Settlement.EncyclopediaLinkWithName);
          return to;
        }
      }

      public ProdigalSonIssueQuest(
        string questId,
        Hero questGiver,
        Hero targetHero,
        Hero prodigalSon,
        Location targetHouse,
        float questDifficulty,
        CampaignTime duration,
        int rewardGold)
        : base(questId, questGiver, duration, rewardGold)
      {
        this._targetHero = targetHero;
        this._prodigalSon = prodigalSon;
        this._targetHouse = targetHouse;
        this._questDifficulty = questDifficulty;
        this.SetDialogs();
        this.InitializeQuestOnCreation();
      }

      protected override void SetDialogs()
      {
        TextObject textObject = new TextObject("{=bQnVtegC}Good, even better. [ib:confident][if:convo_astonished]You can find the house easily when you go to {SETTLEMENT} and walk around the town square. Or you could just speak to this gang leader, {TARGET_HERO.LINK}, and make {?TARGET_HERO.GENDER}her{?}him{\\?} understand and get my boy released. Good luck. I await good news.");
        StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject, textObject);
        Settlement settlement = this._targetHero.CurrentSettlement != null ? this._targetHero.CurrentSettlement : this._targetHero.PartyBelongedTo.HomeSettlement;
        textObject.SetTextVariable("SETTLEMENT", settlement.EncyclopediaLinkWithName);
        this.OfferDialogFlow = DialogFlow.CreateDialogFlow("issue_classic_quest_start").NpcLine(textObject).Condition(new ConversationSentence.OnConditionDelegate(this.is_talking_to_quest_giver)).Consequence(new ConversationSentence.OnConsequenceDelegate(this.QuestAcceptedConsequences)).CloseDialog();
        this.DiscussDialogFlow = DialogFlow.CreateDialogFlow("quest_discuss").NpcLine(new TextObject("{=TkYk5yxn}Yes? Go already. Get our boy back.[if:convo_excited]")).Condition(new ConversationSentence.OnConditionDelegate(this.is_talking_to_quest_giver)).BeginPlayerOptions().PlayerOption(new TextObject("{=kqXxvtwQ}Don't worry I'll free him.")).NpcLine(new TextObject("{=ddEu5IFQ}I hope so.")).Consequence(new ConversationSentence.OnConsequenceDelegate(MapEventHelper.OnConversationEnd)).CloseDialog().PlayerOption(new TextObject("{=Jss9UqZC}I'll go right away")).NpcLine(new TextObject("{=IdKG3IaS}Good to hear that.")).Consequence(new ConversationSentence.OnConsequenceDelegate(MapEventHelper.OnConversationEnd)).CloseDialog().EndPlayerOptions().CloseDialog();
        Campaign.Current.ConversationManager.AddDialogFlow(this.GetTargetHeroDialogFlow(), (object) this);
        Campaign.Current.ConversationManager.AddDialogFlow(this.GetProdigalSonDialogFlow(), (object) this);
      }

      protected override void InitializeQuestOnGameLoad() => this.SetDialogs();

      protected override void HourlyTick()
      {
      }

      protected override void RegisterEvents()
      {
        CampaignEvents.BeforeMissionOpenedEvent.AddNonSerializedListener((object) this, new Action(this.BeforeMissionOpened));
        CampaignEvents.MissionTickEvent.AddNonSerializedListener((object) this, new Action<float>(this.OnMissionTick));
        CampaignEvents.WarDeclared.AddNonSerializedListener((object) this, new Action<IFaction, IFaction, DeclareWarAction.DeclareWarDetail>(this.OnWarDeclared));
        CampaignEvents.OnClanChangedKingdomEvent.AddNonSerializedListener((object) this, new Action<Clan, Kingdom, Kingdom, ChangeKingdomAction.ChangeKingdomActionDetail, bool>(this.OnClanChangedKingdom));
        CampaignEvents.HeroKilledEvent.AddNonSerializedListener((object) this, new Action<Hero, Hero, KillCharacterAction.KillCharacterActionDetail, bool>(this.OnHeroKilled));
        CampaignEvents.MapEventStarted.AddNonSerializedListener((object) this, new Action<MapEvent, PartyBase, PartyBase>(this.OnMapEventStarted));
        CampaignEvents.OnMissionStartedEvent.AddNonSerializedListener((object) this, new Action<IMission>(this.OnMissionStarted));
      }

      private void OnMissionStarted(IMission mission)
      {
        if (CampaignMission.Current?.Location != this._targetHouse)
          return;
        this._isFirstMissionTick = true;
      }

      public override void OnHeroCanHaveQuestOrIssueInfoIsRequested(Hero hero, ref bool result)
      {
        if (hero != this._prodigalSon && hero != this._targetHero)
          return;
        result = false;
      }

      public override void OnHeroCanMoveToSettlementInfoIsRequested(Hero hero, ref bool result)
      {
        if (hero != this._prodigalSon)
          return;
        result = false;
      }

      private void OnMapEventStarted(
        MapEvent mapEvent,
        PartyBase attackerParty,
        PartyBase defenderParty)
      {
        if (!QuestHelper.CheckMinorMajorCoercion((QuestBase) this, mapEvent, attackerParty))
          return;
        QuestHelper.ApplyGenericMinorMajorCoercionConsequences((QuestBase) this, mapEvent);
      }

      private void OnHeroKilled(
        Hero victim,
        Hero killer,
        KillCharacterAction.KillCharacterActionDetail detail,
        bool showNotification = true)
      {
        if (victim != this._targetHero && victim != this._prodigalSon)
          return;
        TextObject textObject = detail == KillCharacterAction.KillCharacterActionDetail.Lost ? this.TargetHeroDisappearedLogText : this.TargetHeroDiedLogText;
        StringHelpers.SetCharacterProperties("QUEST_TARGET", victim.CharacterObject, textObject);
        StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, textObject);
        this.AddLog(textObject);
        this.CompleteQuestWithCancel();
      }

      protected override void OnTimedOut() => this.FinishQuestFail1();

      protected override void OnFinalize() => this._targetHouse.RemoveReservation();

      private void BeforeMissionOpened()
      {
        if (Settlement.CurrentSettlement != this.Settlement || LocationComplex.Current == null)
          return;
        if (LocationComplex.Current.GetLocationOfCharacter(this._prodigalSon) == null)
        {
          this.SpawnProdigalSonInHouse();
          if (!this._isHouseFightFinished)
          {
            this.SpawnThugsInHouse();
            this._isMissionFightInitialized = false;
          }
        }
        foreach (AccompanyingCharacter accompanyingCharacter in PlayerEncounter.LocationEncounter.CharactersAccompanyingPlayer)
        {
          AccompanyingCharacter character = accompanyingCharacter;
          if (!character.CanEnterLocation(this._targetHouse))
            character.AllowEntranceToLocations((Func<Location, bool>) (x => character.CanEnterLocation(x) || x == this._targetHouse));
        }
      }

      private void OnMissionTick(float dt)
      {
        if (CampaignMission.Current.Location != this._targetHouse)
          return;
        Mission current = Mission.Current;
        if (this._isFirstMissionTick)
        {
          Mission.Current.Agents.First<Agent>((Func<Agent, bool>) (x => x.Character == this._prodigalSon.CharacterObject)).GetComponent<CampaignAgentComponent>().AgentNavigator.RemoveBehaviorGroup<AlarmedBehaviorGroup>();
          this._isFirstMissionTick = false;
        }
        if (this._isMissionFightInitialized || this._isHouseFightFinished || current.Agents.Count <= 0)
          return;
        this._isMissionFightInitialized = true;
        MissionFightHandler missionBehavior = current.GetMissionBehavior<MissionFightHandler>();
        List<Agent> opponentSideAgents = new List<Agent>();
        List<Agent> playerSideAgents = new List<Agent>();
        foreach (Agent agent in (List<Agent>) current.Agents)
        {
          if (agent.IsEnemyOf(Agent.Main))
            opponentSideAgents.Add(agent);
          else if (agent.Team == Agent.Main.Team)
            playerSideAgents.Add(agent);
        }
        missionBehavior.StartCustomFight(playerSideAgents, opponentSideAgents, false, false, new MissionFightHandler.OnFightEndDelegate(this.HouseFightFinished));
        foreach (Agent agent in opponentSideAgents)
          agent.Defensiveness = 2f;
      }

      private void OnWarDeclared(
        IFaction faction1,
        IFaction faction2,
        DeclareWarAction.DeclareWarDetail detail)
      {
        if (!this.QuestGiver.MapFaction.IsAtWarWith(Hero.MainHero.MapFaction))
          return;
        if (detail == DeclareWarAction.DeclareWarDetail.CausedByCrimeRatingChange)
        {
          this.RelationshipChangeWithQuestGiver = -5;
          TraitLevelingHelper.OnIssueSolvedThroughQuest(Hero.MainHero, new Tuple<TraitObject, int>[1]
          {
            new Tuple<TraitObject, int>(DefaultTraits.Honor, -50)
          });
        }
        if (DiplomacyHelper.IsWarCausedByPlayer(faction1, faction2, detail))
          this.CompleteQuestWithFail(this.PlayerDeclaredWarQuestLogText);
        else
          this.CompleteQuestWithCancel(detail == DeclareWarAction.DeclareWarDetail.CausedByCrimeRatingChange ? this.CrimeRatingCancelLog : this.WarDeclaredQuestCancelLog);
      }

      private void OnClanChangedKingdom(
        Clan clan,
        Kingdom oldKingdom,
        Kingdom newKingdom,
        ChangeKingdomAction.ChangeKingdomActionDetail detail,
        bool showNotification = true)
      {
        if (clan != Clan.PlayerClan || (newKingdom == null || !newKingdom.IsAtWarWith(this.QuestGiver.MapFaction)) && (newKingdom != null || !clan.IsAtWarWith(this.QuestGiver.MapFaction)))
          return;
        this.CompleteQuestWithCancel(this.WarDeclaredQuestCancelLog);
      }

      private void HouseFightFinished(bool isPlayerSideWon)
      {
        if (isPlayerSideWon)
        {
          Agent agent = Mission.Current.Agents.First<Agent>((Func<Agent, bool>) (x => x.Character == this._prodigalSon.CharacterObject));
          if ((double) agent.Position.Distance(Agent.Main.Position) > (double) agent.GetInteractionDistanceToUsable((IUsable) Agent.Main))
          {
            ScriptBehavior.AddTargetWithDelegate(agent, new ScriptBehavior.SelectTargetDelegate(this.SelectPlayerAsTarget), new ScriptBehavior.OnTargetReachedDelegate(this.OnTargetReached));
          }
          else
          {
            Agent targetAgent = (Agent) null;
            UsableMachine targetUsableMachine = (UsableMachine) null;
            WorldFrame invalid = WorldFrame.Invalid;
            this.OnTargetReached(agent, ref targetAgent, ref targetUsableMachine, ref invalid);
          }
        }
        else
          this.FinishQuestFail2();
        this._isHouseFightFinished = true;
      }

      private bool OnTargetReached(
        Agent agent,
        ref Agent targetAgent,
        ref UsableMachine targetUsableMachine,
        ref WorldFrame targetFrame)
      {
        Mission.Current.GetMissionBehavior<MissionConversationLogic>().StartConversation(agent, false);
        targetAgent = (Agent) null;
        return false;
      }

      private bool SelectPlayerAsTarget(
        Agent agent,
        ref Agent targetAgent,
        ref UsableMachine targetUsableMachine,
        ref WorldFrame targetFrame)
      {
        targetAgent = (Agent) null;
        if ((double) agent.Position.Distance(Agent.Main.Position) > (double) agent.GetInteractionDistanceToUsable((IUsable) Agent.Main))
          targetAgent = Agent.Main;
        return targetAgent != null;
      }

      private void SpawnProdigalSonInHouse()
      {
        this._targetHouse.AddCharacter(new LocationCharacter(new AgentData((IAgentOriginBase) new SimpleAgentOrigin((BasicCharacterObject) this._prodigalSon.CharacterObject)).Monster(TaleWorlds.Core.FaceGen.GetMonsterWithSuffix(this._prodigalSon.CharacterObject.Race, "_settlement")), new LocationCharacter.AddBehaviorsDelegate(SandBoxManager.Instance.AgentBehaviorManager.AddWandererBehaviors), "npc_common", true, LocationCharacter.CharacterRelations.Neutral, (string) null, true));
      }

      private void SpawnThugsInHouse()
      {
        CharacterObject characterObject1 = MBObjectManager.Instance.GetObject<CharacterObject>("gangster_1");
        CharacterObject characterObject2 = MBObjectManager.Instance.GetObject<CharacterObject>("gangster_2");
        CharacterObject characterObject3 = MBObjectManager.Instance.GetObject<CharacterObject>("gangster_3");
        List<CharacterObject> characterObjectList = new List<CharacterObject>();
        if ((double) this._questDifficulty < 0.40000000596046448)
        {
          characterObjectList.Add(characterObject1);
          characterObjectList.Add(characterObject1);
          if ((double) this._questDifficulty >= 0.20000000298023224)
            characterObjectList.Add(characterObject2);
        }
        else if ((double) this._questDifficulty < 0.60000002384185791)
        {
          characterObjectList.Add(characterObject1);
          characterObjectList.Add(characterObject2);
          characterObjectList.Add(characterObject2);
        }
        else
        {
          characterObjectList.Add(characterObject2);
          characterObjectList.Add(characterObject3);
          characterObjectList.Add(characterObject3);
        }
        foreach (CharacterObject troop in characterObjectList)
          this._targetHouse.AddCharacter(new LocationCharacter(new AgentData((IAgentOriginBase) new SimpleAgentOrigin((BasicCharacterObject) troop)).Monster(TaleWorlds.Core.FaceGen.GetMonsterWithSuffix(troop.Race, "_settlement")), new LocationCharacter.AddBehaviorsDelegate(SandBoxManager.Instance.AgentBehaviorManager.AddWandererBehaviors), "npc_common", true, LocationCharacter.CharacterRelations.Enemy, (string) null, true));
      }

      private void QuestAcceptedConsequences()
      {
        this.StartQuest();
        this.AddTrackedObject((ITrackableCampaignObject) this.Settlement);
        this.AddTrackedObject((ITrackableCampaignObject) this._targetHero);
        this.AddLog(this.QuestStartedLog);
      }

      private DialogFlow GetProdigalSonDialogFlow()
      {
        return DialogFlow.CreateDialogFlow("start", 125).NpcLine("{=DYq30shK}Thank you, {?PLAYER.GENDER}milady{?}sir{\\?}.").Condition((ConversationSentence.OnConditionDelegate) (() => Hero.OneToOneConversationHero == this._prodigalSon)).NpcLine("{=K8TSoRSD}Did {?QUEST_GIVER.GENDER}Lady{?}Lord{\\?} {QUEST_GIVER.LINK} send you to rescue me?").Condition((ConversationSentence.OnConditionDelegate) (() =>
        {
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject);
          return true;
        })).PlayerLine("{=ln3bGyIO}Yes, I'm here to take you back.").NpcLine("{=evIohG6b}Thank you, but there's no need. Once we are out of here I can manage to return on my own.[if:convo_happy] I appreciate your efforts. I'll tell everyone in my clan of your heroism.").NpcLine("{=qsJxhNGZ}Safe travels {?PLAYER.GENDER}milady{?}sir{\\?}.").Consequence((ConversationSentence.OnConsequenceDelegate) (() =>
        {
          Mission.Current.Agents.First<Agent>((Func<Agent, bool>) (x => x.Character == this._prodigalSon.CharacterObject)).GetComponent<CampaignAgentComponent>().AgentNavigator.GetBehaviorGroup<DailyBehaviorGroup>().DisableScriptedBehavior();
          Campaign.Current.ConversationManager.ConversationEndOneShot += new Action(this.OnEndHouseMissionDialog);
        })).CloseDialog();
      }

      private DialogFlow GetTargetHeroDialogFlow()
      {
        DialogFlow dialog = DialogFlow.CreateDialogFlow("start", 125).BeginNpcOptions().NpcOption(new TextObject("{=M0vxXQGB}Yes? Do you have something to say?[ib:closed][if:convo_nonchalant]"), (ConversationSentence.OnConditionDelegate) (() => Hero.OneToOneConversationHero == this._targetHero && !this._playerTalkedToTargetHero)).Consequence((ConversationSentence.OnConsequenceDelegate) (() =>
        {
          StringHelpers.SetCharacterProperties("PRODIGAL_SON", this._prodigalSon.CharacterObject);
          this._playerTalkedToTargetHero = true;
        })).PlayerLine("{=K5DgDU2a}I am here for the boy. {PRODIGAL_SON.LINK}. You know who I mean.").GotoDialogState("start").NpcOption(new TextObject("{=I979VDEn}Yes, did you bring {GOLD_AMOUNT}{GOLD_ICON}? [ib:hip][if:convo_stern]That's what he owes... With an interest of course."), (ConversationSentence.OnConditionDelegate) (() =>
        {
          int num = Hero.OneToOneConversationHero != this._targetHero ? 0 : (this._playerTalkedToTargetHero ? 1 : 0);
          if (num == 0)
            return num != 0;
          MBTextManager.SetTextVariable("GOLD_AMOUNT", this.DebtWithInterest);
          return num != 0;
        })).BeginPlayerOptions().PlayerOption("{=IboStvbL}Here is the money, now release him!").ClickableCondition((ConversationSentence.OnClickableConditionDelegate) ((out TextObject explanation) =>
        {
          bool targetHeroDialogFlow = false;
          if (Hero.MainHero.Gold >= this.DebtWithInterest)
          {
            explanation = TextObject.Empty;
            targetHeroDialogFlow = true;
          }
          else
          {
            explanation = new TextObject("{=YuLLsAUb}You don't have {GOLD_AMOUNT}{GOLD_ICON}.");
            explanation.SetTextVariable("GOLD_AMOUNT", this.DebtWithInterest);
          }
          return targetHeroDialogFlow;
        })).NpcLine("{=7k03GxZ1}It's great doing business with you. I'll order my men to release him immediately.[if:convo_mocking_teasing]").Consequence(new ConversationSentence.OnConsequenceDelegate(this.FinishQuestSuccess4)).CloseDialog().PlayerOption("{=9pTkQ5o2}It would be in your interest to let this young nobleman go...").Condition((ConversationSentence.OnConditionDelegate) (() => !this._playerTriedToPersuade)).Consequence((ConversationSentence.OnConsequenceDelegate) (() =>
        {
          this._playerTriedToPersuade = true;
          this._task = this.GetPersuasionTask();
          this.persuasion_start_on_consequence();
        })).GotoDialogState("persuade_gang_start_reservation").PlayerOption("{=AwZhx2tT}I will be back.").NpcLine("{=0fp67gxl}Have a good day.").CloseDialog().EndPlayerOptions().EndNpcOptions();
        this.AddPersuasionDialogs(dialog);
        return dialog;
      }

      private void AddPersuasionDialogs(DialogFlow dialog)
      {
        dialog.AddDialogLine("persuade_gang_introduction", "persuade_gang_start_reservation", "persuade_gang_player_option", "{=EIsQnfLP}Tell me how it's in my interest...[ib:closed][if:convo_nonchalant]", new ConversationSentence.OnConditionDelegate(this.persuasion_start_on_condition), (ConversationSentence.OnConsequenceDelegate) null, (object) this);
        dialog.AddDialogLine("persuade_gang_success", "persuade_gang_start_reservation", "close_window", "{=alruamIW}Hmm... You may be right. It's not worth it. I'll release the boy immediately.[ib:hip][if:convo_pondering]", new ConversationSentence.OnConditionDelegate(ConversationManager.GetPersuasionProgressSatisfied), new ConversationSentence.OnConsequenceDelegate(this.persuasion_success_on_consequence), (object) this, int.MaxValue);
        dialog.AddDialogLine("persuade_gang_failed", "persuade_gang_start_reservation", "start", "{=1YGgXOB7}Meh... Do you think ruling the streets of a city is easy? You underestimate us. Now, about the money.[ib:closed2][if:convo_nonchalant]", (ConversationSentence.OnConditionDelegate) null, new ConversationSentence.OnConsequenceDelegate(ConversationManager.EndPersuasion), (object) this);
        DialogFlow dialogFlow1 = dialog;
        ConversationSentence.OnConditionDelegate conditionDelegate1 = new ConversationSentence.OnConditionDelegate(this.persuasion_select_option_1_on_condition);
        ConversationSentence.OnConsequenceDelegate consequenceDelegate1 = new ConversationSentence.OnConsequenceDelegate(this.persuasion_select_option_1_on_consequence);
        ConversationSentence.OnPersuasionOptionDelegate persuasionOptionDelegate1 = new ConversationSentence.OnPersuasionOptionDelegate(this.persuasion_setup_option_1);
        ConversationSentence.OnClickableConditionDelegate clickableConditionDelegate1 = new ConversationSentence.OnClickableConditionDelegate(this.persuasion_clickable_option_1_on_condition);
        ConversationSentence.OnPersuasionOptionDelegate persuasionOptionDelegate2 = persuasionOptionDelegate1;
        dialogFlow1.AddPlayerLine("persuade_gang_player_option_1", "persuade_gang_player_option", "persuade_gang_player_option_response", "{=!}{PERSUADE_GANG_ATTEMPT_1}", conditionDelegate1, consequenceDelegate1, (object) this, clickableConditionDelegate: clickableConditionDelegate1, persuasionOptionDelegate: persuasionOptionDelegate2);
        DialogFlow dialogFlow2 = dialog;
        ConversationSentence.OnConditionDelegate conditionDelegate2 = new ConversationSentence.OnConditionDelegate(this.persuasion_select_option_2_on_condition);
        ConversationSentence.OnConsequenceDelegate consequenceDelegate2 = new ConversationSentence.OnConsequenceDelegate(this.persuasion_select_option_2_on_consequence);
        ConversationSentence.OnPersuasionOptionDelegate persuasionOptionDelegate3 = new ConversationSentence.OnPersuasionOptionDelegate(this.persuasion_setup_option_2);
        ConversationSentence.OnClickableConditionDelegate clickableConditionDelegate2 = new ConversationSentence.OnClickableConditionDelegate(this.persuasion_clickable_option_2_on_condition);
        ConversationSentence.OnPersuasionOptionDelegate persuasionOptionDelegate4 = persuasionOptionDelegate3;
        dialogFlow2.AddPlayerLine("persuade_gang_player_option_2", "persuade_gang_player_option", "persuade_gang_player_option_response", "{=!}{PERSUADE_GANG_ATTEMPT_2}", conditionDelegate2, consequenceDelegate2, (object) this, clickableConditionDelegate: clickableConditionDelegate2, persuasionOptionDelegate: persuasionOptionDelegate4);
        DialogFlow dialogFlow3 = dialog;
        ConversationSentence.OnConditionDelegate conditionDelegate3 = new ConversationSentence.OnConditionDelegate(this.persuasion_select_option_3_on_condition);
        ConversationSentence.OnConsequenceDelegate consequenceDelegate3 = new ConversationSentence.OnConsequenceDelegate(this.persuasion_select_option_3_on_consequence);
        ConversationSentence.OnPersuasionOptionDelegate persuasionOptionDelegate5 = new ConversationSentence.OnPersuasionOptionDelegate(this.persuasion_setup_option_3);
        ConversationSentence.OnClickableConditionDelegate clickableConditionDelegate3 = new ConversationSentence.OnClickableConditionDelegate(this.persuasion_clickable_option_3_on_condition);
        ConversationSentence.OnPersuasionOptionDelegate persuasionOptionDelegate6 = persuasionOptionDelegate5;
        dialogFlow3.AddPlayerLine("persuade_gang_player_option_3", "persuade_gang_player_option", "persuade_gang_player_option_response", "{=!}{PERSUADE_GANG_ATTEMPT_3}", conditionDelegate3, consequenceDelegate3, (object) this, clickableConditionDelegate: clickableConditionDelegate3, persuasionOptionDelegate: persuasionOptionDelegate6);
        dialog.AddDialogLine("persuade_gang_option_reaction", "persuade_gang_player_option_response", "persuade_gang_start_reservation", "{=!}{PERSUASION_REACTION}", new ConversationSentence.OnConditionDelegate(this.persuasion_selected_option_response_on_condition), new ConversationSentence.OnConsequenceDelegate(this.persuasion_selected_option_response_on_consequence), (object) this);
      }

      private bool is_talking_to_quest_giver() => Hero.OneToOneConversationHero == this.QuestGiver;

      private bool persuasion_start_on_condition()
      {
        return Hero.OneToOneConversationHero == this._targetHero && !ConversationManager.GetPersuasionIsFailure() && this._task.Options.Any<PersuasionOptionArgs>((Func<PersuasionOptionArgs, bool>) (x => !x.IsBlocked));
      }

      private void persuasion_selected_option_response_on_consequence()
      {
        Tuple<PersuasionOptionArgs, PersuasionOptionResult> tuple = ConversationManager.GetPersuasionChosenOptions().Last<Tuple<PersuasionOptionArgs, PersuasionOptionResult>>();
        float difficulty = Campaign.Current.Models.PersuasionModel.GetDifficulty(PersuasionDifficulty.Hard);
        float moveToNextStageChance;
        float blockRandomOptionChance;
        Campaign.Current.Models.PersuasionModel.GetEffectChances(tuple.Item1, out moveToNextStageChance, out blockRandomOptionChance, difficulty);
        this._task.ApplyEffects(moveToNextStageChance, blockRandomOptionChance);
      }

      private bool persuasion_selected_option_response_on_condition()
      {
        PersuasionOptionResult optionResult = ConversationManager.GetPersuasionChosenOptions().Last<Tuple<PersuasionOptionArgs, PersuasionOptionResult>>().Item2;
        MBTextManager.SetTextVariable("PERSUASION_REACTION", PersuasionHelper.GetDefaultPersuasionOptionReaction(optionResult), false);
        if (optionResult == PersuasionOptionResult.CriticalFailure)
          this._task.BlockAllOptions();
        return true;
      }

      private bool persuasion_select_option_1_on_condition()
      {
        if (this._task.Options.Count <= 0)
          return false;
        TextObject text = new TextObject("{=bSo9hKwr}{PERSUASION_OPTION_LINE} {SUCCESS_CHANCE}");
        text.SetTextVariable("SUCCESS_CHANCE", PersuasionHelper.ShowSuccess(this._task.Options.ElementAt<PersuasionOptionArgs>(0), false));
        text.SetTextVariable("PERSUASION_OPTION_LINE", this._task.Options.ElementAt<PersuasionOptionArgs>(0).Line);
        MBTextManager.SetTextVariable("PERSUADE_GANG_ATTEMPT_1", text, false);
        return true;
      }

      private bool persuasion_select_option_2_on_condition()
      {
        if (this._task.Options.Count <= 1)
          return false;
        TextObject text = new TextObject("{=bSo9hKwr}{PERSUASION_OPTION_LINE} {SUCCESS_CHANCE}");
        text.SetTextVariable("SUCCESS_CHANCE", PersuasionHelper.ShowSuccess(this._task.Options.ElementAt<PersuasionOptionArgs>(1), false));
        text.SetTextVariable("PERSUASION_OPTION_LINE", this._task.Options.ElementAt<PersuasionOptionArgs>(1).Line);
        MBTextManager.SetTextVariable("PERSUADE_GANG_ATTEMPT_2", text, false);
        return true;
      }

      private bool persuasion_select_option_3_on_condition()
      {
        if (this._task.Options.Count <= 2)
          return false;
        TextObject text = new TextObject("{=bSo9hKwr}{PERSUASION_OPTION_LINE} {SUCCESS_CHANCE}");
        text.SetTextVariable("SUCCESS_CHANCE", PersuasionHelper.ShowSuccess(this._task.Options.ElementAt<PersuasionOptionArgs>(2), false));
        text.SetTextVariable("PERSUASION_OPTION_LINE", this._task.Options.ElementAt<PersuasionOptionArgs>(2).Line);
        MBTextManager.SetTextVariable("PERSUADE_GANG_ATTEMPT_3", text, false);
        return true;
      }

      private void persuasion_select_option_1_on_consequence()
      {
        if (this._task.Options.Count <= 0)
          return;
        this._task.Options[0].BlockTheOption(true);
      }

      private void persuasion_select_option_2_on_consequence()
      {
        if (this._task.Options.Count <= 1)
          return;
        this._task.Options[1].BlockTheOption(true);
      }

      private void persuasion_select_option_3_on_consequence()
      {
        if (this._task.Options.Count <= 2)
          return;
        this._task.Options[2].BlockTheOption(true);
      }

      private PersuasionOptionArgs persuasion_setup_option_1()
      {
        return this._task.Options.ElementAt<PersuasionOptionArgs>(0);
      }

      private PersuasionOptionArgs persuasion_setup_option_2()
      {
        return this._task.Options.ElementAt<PersuasionOptionArgs>(1);
      }

      private PersuasionOptionArgs persuasion_setup_option_3()
      {
        return this._task.Options.ElementAt<PersuasionOptionArgs>(2);
      }

      private bool persuasion_clickable_option_1_on_condition(out TextObject hintText)
      {
        hintText = new TextObject("{=9ACJsI6S}Blocked");
        if (this._task.Options.Count <= 0)
          return false;
        hintText = this._task.Options.ElementAt<PersuasionOptionArgs>(0).IsBlocked ? hintText : TextObject.Empty;
        return !this._task.Options.ElementAt<PersuasionOptionArgs>(0).IsBlocked;
      }

      private bool persuasion_clickable_option_2_on_condition(out TextObject hintText)
      {
        hintText = new TextObject("{=9ACJsI6S}Blocked");
        if (this._task.Options.Count <= 1)
          return false;
        hintText = this._task.Options.ElementAt<PersuasionOptionArgs>(1).IsBlocked ? hintText : TextObject.Empty;
        return !this._task.Options.ElementAt<PersuasionOptionArgs>(1).IsBlocked;
      }

      private bool persuasion_clickable_option_3_on_condition(out TextObject hintText)
      {
        hintText = new TextObject("{=9ACJsI6S}Blocked");
        if (this._task.Options.Count <= 2)
          return false;
        hintText = this._task.Options.ElementAt<PersuasionOptionArgs>(2).IsBlocked ? hintText : TextObject.Empty;
        return !this._task.Options.ElementAt<PersuasionOptionArgs>(2).IsBlocked;
      }

      private void persuasion_success_on_consequence()
      {
        ConversationManager.EndPersuasion();
        this.FinishQuestSuccess3();
      }

      private void OnEndHouseMissionDialog()
      {
        Campaign.Current.GameMenuManager.NextLocation = LocationComplex.Current.GetLocationWithId("center");
        Campaign.Current.GameMenuManager.PreviousLocation = CampaignMission.Current.Location;
        Mission.Current.EndMission();
        this.FinishQuestSuccess1();
      }

      private PersuasionTask GetPersuasionTask()
      {
        PersuasionTask persuasionTask = new PersuasionTask(0);
        persuasionTask.FinalFailLine = TextObject.Empty;
        persuasionTask.TryLaterLine = TextObject.Empty;
        persuasionTask.SpokenLine = new TextObject("{=6P1ruzsC}Maybe...");
        persuasionTask.AddOptionToTask(new PersuasionOptionArgs(DefaultSkills.Charm, DefaultTraits.Calculating, TraitEffect.Positive, PersuasionArgumentStrength.ExtremelyHard, true, new TextObject("{=Lol4clzR}Look, it was a good try, but they're not going to pay. Releasing the kid is the only move that makes sense.")));
        persuasionTask.AddOptionToTask(new PersuasionOptionArgs(DefaultSkills.Roguery, DefaultTraits.Mercy, TraitEffect.Negative, PersuasionArgumentStrength.Hard, false, new TextObject("{=wJCVlVF7}These nobles aren't like you and me. They've kept their wealth by crushing people like you for generations. Don't mess with them.")));
        persuasionTask.AddOptionToTask(new PersuasionOptionArgs(DefaultSkills.Roguery, DefaultTraits.Generosity, TraitEffect.Positive, PersuasionArgumentStrength.Normal, false, new TextObject("{=o1KOn4WZ}If you let this boy go, his family will remember you did them a favor. That's a better deal for you than a fight you can't hope to win.")));
        return persuasionTask;
      }

      private void persuasion_start_on_consequence()
      {
        ConversationManager.StartPersuasion(2f, 1f, 1f, 2f, 2f, 0.0f, PersuasionDifficulty.Hard);
      }

      private void FinishQuestSuccess1()
      {
        this.CompleteQuestWithSuccess();
        this.AddLog(this.PlayerDefeatsThugsQuestSuccessLog);
        ChangeRelationAction.ApplyPlayerRelation(this.QuestGiver, 5);
        GainRenownAction.Apply(Hero.MainHero, 3f);
        GiveGoldAction.ApplyForQuestBetweenCharacters(this.QuestGiver, Hero.MainHero, this.RewardGold);
      }

      private void FinishQuestSuccess3()
      {
        this.CompleteQuestWithSuccess();
        this.AddLog(this.PlayerConvincesGangLeaderQuestSuccessLog);
        ChangeRelationAction.ApplyPlayerRelation(this.QuestGiver, 5);
        GainRenownAction.Apply(Hero.MainHero, 1f);
        GiveGoldAction.ApplyForQuestBetweenCharacters(this.QuestGiver, Hero.MainHero, this.RewardGold);
      }

      private void FinishQuestSuccess4()
      {
        GainRenownAction.Apply(Hero.MainHero, 1f);
        GiveGoldAction.ApplyForQuestBetweenCharacters(Hero.MainHero, this._targetHero, this.DebtWithInterest);
        this.CompleteQuestWithSuccess();
        this.AddLog(this.PlayerPaysTheDebtQuestSuccessLog);
        ChangeRelationAction.ApplyPlayerRelation(this.QuestGiver, 5);
        GiveGoldAction.ApplyForQuestBetweenCharacters(this.QuestGiver, Hero.MainHero, this.RewardGold);
      }

      private void FinishQuestFail1()
      {
        this.AddLog(this.QuestTimeOutFailLog);
        ChangeRelationAction.ApplyPlayerRelation(this.QuestGiver, -5);
      }

      private void FinishQuestFail2()
      {
        this.CompleteQuestWithFail();
        this.AddLog(this.PlayerHasDefeatedQuestFailLog);
        ChangeRelationAction.ApplyPlayerRelation(this.QuestGiver, -5);
      }

      internal static void AutoGeneratedStaticCollectObjectsProdigalSonIssueQuest(
        object o,
        List<object> collectedObjects)
      {
        ((MBObjectBase) o).AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      protected override void AutoGeneratedInstanceCollectObjects(List<object> collectedObjects)
      {
        base.AutoGeneratedInstanceCollectObjects(collectedObjects);
        collectedObjects.Add((object) this._targetHero);
        collectedObjects.Add((object) this._prodigalSon);
        collectedObjects.Add((object) this._targetHouse);
      }

      internal static object AutoGeneratedGetMemberValue_targetHero(object o)
      {
        return (object) ((ProdigalSonIssueBehavior.ProdigalSonIssueQuest) o)._targetHero;
      }

      internal static object AutoGeneratedGetMemberValue_prodigalSon(object o)
      {
        return (object) ((ProdigalSonIssueBehavior.ProdigalSonIssueQuest) o)._prodigalSon;
      }

      internal static object AutoGeneratedGetMemberValue_playerTalkedToTargetHero(object o)
      {
        return (object) ((ProdigalSonIssueBehavior.ProdigalSonIssueQuest) o)._playerTalkedToTargetHero;
      }

      internal static object AutoGeneratedGetMemberValue_targetHouse(object o)
      {
        return (object) ((ProdigalSonIssueBehavior.ProdigalSonIssueQuest) o)._targetHouse;
      }

      internal static object AutoGeneratedGetMemberValue_questDifficulty(object o)
      {
        return (object) ((ProdigalSonIssueBehavior.ProdigalSonIssueQuest) o)._questDifficulty;
      }

      internal static object AutoGeneratedGetMemberValue_isHouseFightFinished(object o)
      {
        return (object) ((ProdigalSonIssueBehavior.ProdigalSonIssueQuest) o)._isHouseFightFinished;
      }

      internal static object AutoGeneratedGetMemberValue_playerTriedToPersuade(object o)
      {
        return (object) ((ProdigalSonIssueBehavior.ProdigalSonIssueQuest) o)._playerTriedToPersuade;
      }
    }
  }
}
